package us.k5rud.template;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

// -------------------------------------------------------------------------------------------------------
class TemplateThread extends Thread {
	private boolean mSuspend;

	private final TemplateSurfaceView mSurfView;
	static final String TAG = "TemplateThread";
	SurfaceHolder mSurfHolder;

	// -------------------------------------------------------------------------------------------------------
	TemplateThread(TemplateSurfaceView templateSurfaceView, SurfaceHolder sh) {
		mSurfHolder = sh;
		mSurfView = templateSurfaceView;
		mSuspend = true;
	}
	// -------------------------------------------------------------------------------------------------------
	public void die() {
		Log.v(TAG, "die start");
		try {
			Log.v(TAG, "die interrupt");
			interrupt();
			Log.v(TAG, "die join");
			join();
			Log.v(TAG, "die join done");
		}
		catch (InterruptedException ex) { // thrown when another thread joins
			Log.v(TAG, "die exception");
		}
		Log.v(TAG, "die done");
	}
	// -------------------------------------------------------------------------------------------------------
	@Override
	public void run() {
		Log.v(TAG, "run start");

		while (true) {
			try {
				Log.v(TAG, "sleep");
				sleep(250);

				synchronized (this) {
					while (mSuspend) {
						Log.v(TAG, "run suspend");
						wait();
					}
				}
			}
			catch (InterruptedException ie) {
				Log.v(TAG, "run exception");
				break;
			}
			performTask();
		}
		Log.v(TAG, "run done");
	}
	// -------------------------------------------------------------------------------------------------------
	public synchronized void pause() {
		mSuspend = true;
	}
	// -------------------------------------------------------------------------------------------------------
	public synchronized void unpause() {
		mSuspend = false;
		notify();
	}
	// -------------------------------------------------------------------------------------------------------
	private void performTask() {
		Canvas canvas = mSurfHolder.lockCanvas();
		if (canvas != null) {
			mSurfView.doDraw(canvas);
			mSurfHolder.unlockCanvasAndPost(canvas);
		}
		else {
			Log.v(TAG, "no surface");
		}
	}
}
